Skip to content

Interface 类基础

gradio.Interface 是 Gradio 中最核心和最常用的类。它提供了一种非常简单和直接的方式,让你能够为任何 Python 函数快速创建一个交互式的 Web 用户界面。如果你想快速展示你的机器学习模型、数据处理脚本或任何 Python 功能,Interface 类是你的首选。

核心概念:fn, inputs, outputs

构建一个 Interface 应用至少需要三个关键参数:

  1. fn:你想要创建 UI 的 Python 函数。这个函数将接收来自输入组件的数据,并返回在输出组件中显示的结果。
  2. inputs:一个 Gradio 输入组件或一个输入组件的列表。这些组件定义了用户如何向你的函数提供数据。
  3. outputs:一个 Gradio 输出组件或一个输出组件的列表。这些组件定义了函数返回的结果如何展示给用户。

简单示例

python
import gradio as gr

# 1. 定义你的核心函数
def greet(name, is_morning, temperature):
    salutation = "早上好" if is_morning else "你好"
    greeting = f"{salutation}{name}!今天是 {temperature}°C。"
    return greeting

# 2. 创建 Interface
demo = gr.Interface(
    fn=greet, # 你的函数
    inputs=[
        gr.Textbox(label="你的名字", info="请输入你的称呼"),
        gr.Checkbox(label="现在是早上吗?"),
        gr.Slider(minimum=-10, maximum=40, label="温度 (°C)", info="拖动滑块选择当前温度")
    ],
    outputs=gr.Textbox(label="问候语") # 输出组件
)

# 3. 启动应用
# demo.launch() # 在本地环境中取消注释以运行

在这个例子中:

  • greet 函数接收三个参数:name (字符串), is_morning (布尔值), temperature (数字)。
  • inputs 列表包含三个组件:一个 gr.Textbox 用于输入名字,一个 gr.Checkbox 用于选择是否是早上,一个 gr.Slider 用于选择温度。这些组件会按顺序映射到 greet 函数的参数。
  • outputs 是一个 gr.Textbox,用于显示 greet 函数返回的问候语字符串。

指定输入输出组件

Gradio 提供了多种方式来指定输入和输出组件:

1. 组件实例 (推荐)

最明确和可配置的方式是直接使用 Gradio 组件类的实例,例如 gr.Textbox(), gr.Image(), gr.Slider() 等。这允许你设置组件的各种属性,如 label (标签), info (提示信息), placeholder (占位符文本), choices (选项列表) 等。

python
inputs = [
    gr.Image(type="pil", label="上传图片"), # PIL Image for input
    gr.Radio(["效果A", "效果B", "效果C"], label="选择效果")
]
outputs = gr.Image(type="pil", label="处理后的图片") # PIL Image for output

2. 字符串快捷方式 (适用于简单场景)

对于一些常见的组件,Gradio 提供了字符串快捷方式。这对于快速原型设计很方便,但配置选项有限。

  • "text""textbox": 对应 gr.Textbox()
  • "number": 对应 gr.Number()
  • "slider": 对应 gr.Slider()
  • "checkbox": 对应 gr.Checkbox()
  • "image": 对应 gr.Image()
  • "audio": 对应 gr.Audio()
  • "video": 对应 gr.Video()
  • "file": 对应 gr.File()
  • "pil": 对应 gr.Image(type="pil") (Pillow 图像对象)
  • "numpy": 对应 gr.Image(type="numpy") (NumPy 数组)
  • "plot": 对应 gr.Plot() (Matplotlib 图表)
  • "label": 对应 gr.Label() (分类标签)
  • "dataframe": 对应 gr.DataFrame() (Pandas DataFrame)
python
inputs = ["image", "text"] # 等同于 [gr.Image(), gr.Textbox()]
outputs = "label"

注意:当你的函数期望特定类型的数据(例如,Pillow 图像而不是文件路径,或者 NumPy 数组),或者你需要自定义组件标签、默认值等时,强烈建议使用完整的组件实例而不是字符串快捷方式。

单个输入/输出

如果你的函数只有一个输入或一个输出,你可以直接传递单个组件实例或字符串,而无需将其放入列表中。

python
def welcome(name):
  return f"欢迎, {name}!"

demo = gr.Interface(fn=welcome, inputs="textbox", outputs="textbox")

添加元信息

为了让你的应用更易于理解和使用,可以添加标题、描述和详细说明:

  • title: 界面的主标题。
  • description: 显示在标题下方的一段简短描述。
  • article: 显示在界面组件下方的一段较长的文本,支持 Markdown 格式。你可以用它来提供详细的使用说明、引用来源、模型介绍等。
python
article_content = """
## 关于此应用
这是一个简单的问候应用,演示了 `gr.Interface` 的基本用法。

### 如何使用:
1. 输入你的名字。
2. 选择是否是早上。
3. 调整温度滑块。
4. 点击 "Submit" 查看结果。
"""

demo = gr.Interface(
    fn=greet,
    inputs=["text", "checkbox", "slider"],
    outputs="text",
    title="智能问候机器人 V2",
    description="一个能根据时间和温度生成个性化问候的应用。",
    article=article_content
)

提供示例 (examples)

examples 参数允许你为用户提供一些预设的输入,方便他们快速了解和测试你的应用。它应该是一个列表的列表,其中每个内部列表代表一组输入值,其顺序和类型应与 inputs 参数匹配。

python
def calculate_bmi(height_cm, weight_kg):
    if height_cm <= 0 or weight_kg <= 0:
        return "请输入有效身高和体重", ""
    bmi = weight_kg / ((height_cm / 100) ** 2)
    category = ""
    if bmi < 18.5:
        category = "过轻"
    elif 18.5 <= bmi < 24:
        category = "正常"
    elif 24 <= bmi < 28:
        category = "过重"
    else:
        category = "肥胖"
    return f"{bmi:.2f}", category

bmi_demo = gr.Interface(
    fn=calculate_bmi,
    inputs=[
        gr.Number(label="身高 (cm)"),
        gr.Number(label="体重 (kg)")
    ],
    outputs=[
        gr.Textbox(label="BMI 值"),
        gr.Label(label="健康状况")
    ],
    title="BMI 计算器",
    description="输入身高和体重计算身体质量指数 (BMI)。",
    examples=[
        [170, 65],
        [160, 70],
        [180, 55]
    ]
)
# bmi_demo.launch()
  • cache_examples=True (默认 False):如果设置为 True,Gradio 会预先计算并缓存示例的输出。这可以加快用户点击示例时的响应速度,但会增加应用的初始启动时间。

启动应用 (launch())

创建 Interface 实例后,调用其 launch() 方法来启动 Web 服务器并使应用可访问。

python
demo.launch()

launch() 方法有一些常用参数:

  • inline (默认为 False,但在 Jupyter/Colab Notebooks 中通常为 True):如果为 True,应用会直接嵌入到 Notebook 的输出单元格中。
  • inbrowser (默认为 False):如果为 True,应用会在新的浏览器标签页中自动打开。
  • server_name (默认为 "127.0.0.1"):绑定的服务器名称。设置为 "0.0.0.0" 可以在局域网内访问。
  • server_port (默认为 7860):绑定的服务器端口。如果端口已被占用,Gradio 会尝试使用下一个可用端口。
  • share (默认为 False,但在 Colab 中为 True):如果为 True,会创建一个临时的公共链接,方便与他人分享。
  • auth (默认为 None):可以设置用户名和密码以保护你的应用。例如 auth=("user", "password")
  • prevent_thread_lock (默认为 False): 在某些环境中 (如 Google Colab),如果 launch() 阻塞了主线程,设置此为 True

Interface 类是 Gradio 的基石,掌握其基础用法是构建更复杂应用的起点。接下来的章节将深入探讨其更多高级特性。


ChatInterface 聊天界面基础

gr.ChatInterface 是 Gradio 针对聊天机器人场景的高级抽象,允许你用极少的代码快速构建现代化的聊天机器人 Web 界面。它内置消息历史、流式输出、多模态输入、用户反馈等功能,适合 LLM、AI 助手等应用。

基础用法

最简单的用法只需定义一个聊天函数,并传递给 gr.ChatInterface

python
import gradio as gr

def echo(message, history):
    return message

demo = gr.ChatInterface(fn=echo, type="messages", examples=["你好", "hello"], title="回声机器人")
demo.launch()
  • message:用户最新输入的消息(字符串)。
  • history:对话历史,格式为 OpenAI 风格的字典列表:[{"role": "user"|"assistant", "content": str}]
  • 返回值:可以是字符串、Gradio 组件、消息字典或消息列表。

主要参数说明

  • fn:聊天函数,签名通常为 (message, history)
  • type:消息格式,推荐 "messages"(OpenAI 风格)。
  • chatbot:自定义 gr.Chatbot 组件,可设置高度、占位符等。
  • textbox:自定义输入框(gr.Textboxgr.MultimodalTextbox)。
  • multimodal:是否启用多模态输入(如图片、文件)。
  • additional_inputs:额外输入组件(如系统提示、参数滑块等)。
  • examples:示例输入,支持文本或多模态。
  • title/description:界面标题和描述。
  • flagging_mode/flagging_options:用户反馈(点赞/点踩/自定义标签)。
  • save_history:是否在浏览器本地保存聊天历史。

进阶用法

1. 流式输出

通过在聊天函数中使用 yield,可实现流式回复:

python
import time
import gradio as gr

def slow_echo(message, history):
    for i in range(len(message)):
        time.sleep(0.05)
        yield "你输入了:" + message[:i+1]

demo = gr.ChatInterface(slow_echo, type="messages")
demo.launch()

2. 多模态输入

启用 multimodal=True,支持文本+文件/图片输入:

python
import gradio as gr

def count_files(message, history):
    num_files = len(message["files"])
    return f"你上传了 {num_files} 个文件"

demo = gr.ChatInterface(
    fn=count_files,
    type="messages",
    multimodal=True,
    examples=[{"text": "你好", "files": []}],
    title="文件计数机器人"
)
demo.launch()

3. 添加额外输入组件

可通过 additional_inputs 添加如系统提示、参数滑块等:

python
import gradio as gr

def chat(message, history, system_prompt, tokens):
    return f"系统提示: {system_prompt}\n消息: {message[:int(tokens)]}"

demo = gr.ChatInterface(
    chat,
    type="messages",
    additional_inputs=[
        gr.Textbox("我是AI助手。", label="系统提示"),
        gr.Slider(10, 100, label="最大字符数")
    ]
)
demo.launch()

4. 返回复杂内容

支持返回图片、音频、文件等 Gradio 组件,或消息列表:

python
import gradio as gr

def multimodal_reply(message, history):
    return [f"你说:{message}", gr.Image(value="cat.png")]

demo = gr.ChatInterface(multimodal_reply, type="messages")
demo.launch()

与 LLM 结合示例

以 OpenAI API 为例,支持流式输出:

python
import os
import gradio as gr
from openai import OpenAI

client = OpenAI(api_key=os.environ.get("OPENAI_API_KEY"))

def predict(message, history):
    history_openai_format = []
    for human, assistant in history:
        history_openai_format.append({"role": "user", "content": human})
        history_openai_format.append({"role": "assistant", "content": assistant})
    history_openai_format.append({"role": "user", "content": message})
    response = client.chat.completions.create(
        model="gpt-3.5-turbo",
        messages=history_openai_format,
        temperature=1.0,
        stream=True
    )
    partial_message = ""
    for chunk in response:
        if chunk.choices[0].delta.content is not None:
            partial_message += chunk.choices[0].delta.content
            yield partial_message

demo = gr.ChatInterface(predict, type="messages")
demo.launch()

用户反馈与历史管理

  • flagging_mode:设置为 "manual" 可启用点赞/点踩反馈。
  • flagging_options:自定义反馈标签。
  • save_history=True:启用后,用户可在侧边栏切换历史对话。
python
import gradio as gr

def slow_echo(message, history):
    for i in range(len(message)):
        yield "你输入了:" + message[:i+1]

demo = gr.ChatInterface(
    slow_echo,
    type="messages",
    flagging_mode="manual",
    flagging_options=["喜欢", "垃圾信息", "不适当", "其他"],
    save_history=True
)
demo.launch()

常见问题与建议

  • 聊天函数必须接收 message, history 两个参数。
  • 返回值可为字符串、Gradio 组件、消息字典或消息列表。
  • 多模态时,message 为字典:{"text": ..., "files": [...]}
  • 支持流式输出(yield),提升用户体验。
  • 可通过 Blocks API 获得更灵活的自定义能力。

更多高级用法详见 Gradio 官方文档


TabbedInterface 选项卡界面基础

gr.TabbedInterface 是 Gradio 提供的用于多模型、多功能演示的高阶界面组件。它允许你将多个 InterfaceBlocks 应用以选项卡(Tab)的形式组合在同一个页面,用户可通过点击不同标签页切换不同功能或模型。

基础用法

最常见的用法是将多个 Interface 实例组合:

python
import gradio as gr

def greet(name):
    return f"你好, {name}!"

def square(x):
    return x ** 2

iface1 = gr.Interface(fn=greet, inputs="text", outputs="text", title="打招呼")
iface2 = gr.Interface(fn=square, inputs="number", outputs="number", title="平方计算")

demo = gr.TabbedInterface(
    [iface1, iface2],
    tab_names=["问候", "求平方"]
)
demo.launch()
  • TabbedInterface 的第一个参数是 Interface/Blocks 实例列表,tab_names 指定每个标签页的名称。
  • 每个标签页可以是不同的功能、模型或数据处理流程。

主要参数说明

  • interfaces:Interface 或 Blocks 实例列表。
  • tab_names:每个标签页的名称(字符串列表)。
  • theme/css:自定义主题或样式。
  • 其他参数同 Interface(如 titledescription 等)。

典型场景

  • 多模型对比:如同一输入在不同模型下的输出效果对比。
  • 多功能工具箱:如 NLP、CV、音频等多种工具集合。
  • 多语言/多任务演示:如中英文问答、分类/生成等多任务切换。

与 Blocks 的关系

  • TabbedInterface 适合快速组合多个独立的 Interface/Blocks。
  • 若需更复杂的自定义布局、嵌套 Tab、交互逻辑,推荐直接使用 gr.Blocks + gr.Tab
python
import gradio as gr

def flip_text(x):
    return x[::-1]

def flip_image(x):
    import numpy as np
    return np.fliplr(x)

with gr.Blocks() as demo:
    gr.Markdown("使用此演示翻转文本或图像文件。")
    with gr.Tab("翻转文本"):
        text_input = gr.Textbox()
        text_output = gr.Textbox()
        text_button = gr.Button("翻转")
        text_button.click(flip_text, inputs=text_input, outputs=text_output)
    with gr.Tab("翻转图像"):
        with gr.Row():
            image_input = gr.Image()
            image_output = gr.Image()
        image_button = gr.Button("翻转")
        image_button.click(flip_image, inputs=image_input, outputs=image_output)

demo.launch()

常见问题与建议

  • 每个 Tab 内的 Interface/Blocks 相互独立,状态不会共享。
  • 若需 Tab 间共享数据,需用 Blocks+State 手动实现。
  • TabbedInterface 适合"多功能集合"场景,若需复杂交互建议用 Blocks。
  • 支持自定义主题、样式,提升整体 UI/UX。

更多高级用法详见 Gradio 官方文档